package com.example.demo.controller.rmqp;

import com.rabbitmq.client.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author 高俊
 * @create 2021-08-2021/8/13-15:29
 */
@Controller
@RequestMapping("/rmqp")
public class RmqpController {
    public static final String  QUEUE = "HELLO";

    @RequestMapping(value = "/send/message",method = RequestMethod.POST)
    @ResponseBody
    public String sendMessage(@RequestBody String textVal) throws Exception{
        Channel channel = RmqpConnection.getConnection();

        /**
         * param1: 队列名称
         * param2: 是否持久化数据
         * param3: 是否共享数据
         * param4: 是否在最后一个用户断开连接的时候删除数据
         * param5: 其他参数
         */
        channel.queueDeclare(QUEUE,false,false,false,null);

        /**
         *param1: 指定发送到的交换机
         *param2: 路由的Key值是那个 本次的是队列名
         *param3: 其他参数信息
         *param4: 发送消息的消息体
         */
        channel.basicPublish("",QUEUE,null,textVal.getBytes());
         acceptMessage();
        return "发送完成.....";
    }

    @RequestMapping("/toTarget")
    public String toTarget(){
        return "target";
    }


    /*@RequestMapping(value = "/accept/message",method = RequestMethod.POST)
    @ResponseBody*/
    public void acceptMessage() throws Exception{
        DeliverCallback deliverCallback = (tag,msg)->{
            String s = new String(msg.getBody());
            System.out.println(s);
        };
        CancelCallback cancelCallback = tag->{
            System.out.println("消息被中断了");
        };

        Channel channel = RmqpConnection.getConnection();



        channel.basicConsume(QUEUE,true,deliverCallback,cancelCallback);
    }

}
